<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <!-- 利用自定义指令来实现对按钮的权限控制 -->
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <!-- 设置默认的排序 -->
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <!-- 利用作用域插槽来获取数据 -->
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment ) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 查询参数传参 query -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/detail?id=${row.id}`)">查看</el-button> -->
              <!-- 路径参数传参  路由要做修改 :id -->
              <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hClose"
      >
        <!--  @close="showDialog=false"点击取消关闭弹层 -->
        <EmpDialog ref="empDialog" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="roleShowDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <AssignRole v-if="roleShowDialog" :role-id="roleId" @close="roleShowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
// 导入枚举文件
import employeesEnum from '@/constant/employees'
import { getEmployees, delEmployees } from '@/api/employees'
import EmpDialog from './empDialog.vue'
const hireType = {}
employeesEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '',
      roleShowDialog: false, // 控制分配角色的弹层
      showDialog: false, // 控制新增员工的弹层
      list: [], // 存储获取的员工信息
      page: 1, // 页码值
      size: 2, // 每页显示多少条
      total: 0 // 保存员工的总数
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRole(id) {
      this.roleId = id
      this.roleShowDialog = true
    },
    // 导出员工列表为excel文件
    async handleDownload() {
      // 1.发送请求获取数据
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code !== 10000) return
        //   2.需要将获取到的额数据转换为excel需要的格式  header data
        console.log(res)
        const { headers, data } = this.dataFoMate(res.data.rows)
        //   3.调用excel.export_json_to_excel 将格式化好的数据写入到excel文件中
        import('@/vendor/Export2Excel').then(excel => {
          // const tHeader = ['姓名', '年龄']
          // const data = [['张三', 25], ['李四', 30]]
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除员工
    hDel(id) {
      this.$confirm('你确定要删除这条数据吗?').then(async() => {
        const res = await delEmployees(id)
        this.$message.success(res.message)
        // 如果删除的是最后一条数据判断此时页面是否只有一条数据 如果有就跳转到上一页,如果是第一页则给page默认值=1
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployees()
      }).catch(err => console.log(err))
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.loadEmployees()
    },
    // 分页-控制每页条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    // 分页-控制页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 枚举格式化聘用形式
    hireTypeFormat(data) {
      // 这样写性能太低下 每次都要进来循环
      // return employeesEnum.hireType.find(item => item.id === data).value
      // 转换成对象形式{1:'正式',2:'非正式'} 只用在上面执行一个forEach循环  这样就大大提高了性能 而且也不会报错
      return hireType[data] || '未知'
    },
    // 加载员工信息
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 将英文键名转换为中文键名
    dataFoMate(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let headers = []
      const one = list[0]
      if (one) {
        headers = Object.keys(one).map(item => {
          return mapInfo[item]
        })
      }
      // console.log(headers)
      // 将每一个对象中的值存储到数组中
      const data = list.map(item => { return Object.values(item) })
      // console.log(data)
      return { headers, data }
    }
  }
}
</script>
